package com.alks.common.aspect;

import com.alibaba.fastjson2.JSON;
import com.alks.common.data.thread.UserIdThread;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
@Slf4j
public class WebLoggerAspect {

    @Pointcut("@annotation(com.alks.common.aop.WebLogger)")
    public void log() {}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
//        System.out.println("URL：" + request.getRequestURL().toString());
            String userId = "";
            String userName = "";
            if (UserIdThread.get() != null) {
                if (UserIdThread.get().getLoginName() != null) {
                    userId = UserIdThread.get().getLoginName();
                }
                if (UserIdThread.get().getUserName() != null) {
                    userName = UserIdThread.get().getUserName();
                }
            }
            String method = request.getMethod();
            StringBuilder paramStr = new StringBuilder();
            if (!"GET".equalsIgnoreCase(method)) {
                Object[] args = joinPoint.getArgs();
                for (Object arg : args) {
                    if (arg instanceof HttpServletRequest || arg instanceof HttpServletResponse
                        || arg instanceof org.springframework.web.multipart.MultipartFile) {
                        continue;
                    }
                    paramStr.append(JSON.toJSONString(arg)).append(" ");
                }
            }
            log.info("URL: {}, 登录名: {}, 用户名字: {}, 请求参数: {}",
                    request.getRequestURI(),
                    userId,
                    userName,
                    paramStr.toString().trim());
        } catch (Exception e) {
            log.warn("日志切面处理异常，不影响主流程: {}", e.getMessage());
        }
    }
}